﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NerdDinner.Core.Entities;
using NerdDinner.Core.Repository;

namespace NerdDinner.Controllers
{
    public class DinnerController : Controller
    {
        protected DinnerRepository _repos;

        public DinnerController()
        {
            _repos = new DinnerRepository();
        }
        //
        // GET: /Dinner/

        public ActionResult Index(int? page, int? pageSize)
        {
            //var pageSize = Request["pageSize"];
            //var page = Request["Page"];
            

            var dinners = _repos.FetchAll();


            ViewData["Dinners"] = dinners;
            ViewData["Page"] = page ?? 1;
            ViewData["PageSize"] = pageSize == null ? 100 : pageSize;
            return View();
        }

        //
        // GET: /Dinner/Details/5

        public ActionResult Details(Guid id)
        {
            ViewData.Model = _repos.Fetch(id);
            return View();
        }

        //
        // GET: /Dinner/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Dinner/Create

        [HttpPost]
        public ActionResult Create(Dinner dinner)
        {
            try
            {
                dinner.Name = Request["name"] + "request";
                _repos.Create(dinner);


                if(Request.IsAjaxRequest())
                {
                    return new JsonResult() { Data = dinner};
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Dinner/Edit/5
 
        public ActionResult Edit(Guid id)
        {
            var dinner = _repos.Fetch(id);

            ViewData.Model = dinner;

            return View();
        }

        //
        // POST: /Dinner/Edit/5

        [HttpPost]
        public ActionResult Edit(Dinner dinner)
        {
            try
            {
                _repos.Update(dinner);
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
